<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);

require_once "lib/WxPay.Api.php";
$data=$xml = simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA']);
if($data->attach==1){
	require_once "lib/WxPay.Config.php";
}else{
	require_once "lib/WxPay.Config2.php";
}
require_once 'lib/WxPay.Notify.php';
require_once 'log.php';

//初始化日志
$logHandler= new CLogFileHandler("logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

require_once('../../global.php');
require_once('sqinc/inc/common.inc.php');
class PayNotifyCallBack extends WxPayNotify
{
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);
		Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}
	
	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{
		global $db2;
		$notfiyOutput = array();		
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}
		$orders=explode(",",$data['out_trade_no']);
		$ordernum=count($orders);
		if($ordernum!=1){
			$order=$orders[0];
			foreach($orders as $value){
				if(checktrade($value,1,1)==1){
					if(checktrade($value,1)==1){
						if(!updatetrade($value,2,1)){
							$paystate=5;
						}
					}
					if(checkorder($value)){
						if(checkorder($value,1)){
							$order=$db2->select(3,"tb_trade","tradeid",array("orderid"=>$db2->select(3,'tb_trade','orderid',array('tradeid'=>$value)),"tradeid[!]"=>$value));
							if(!updatetrade($order,2,0)){
								$paystate=6;
							}
						}
					}
				}else{
					$paystate=3;
				}
			}
		}else{
			$order=$data['out_trade_no'];
			if(checktrade($order,1,1)==1){
				if(checktrade($order,1)==1){
					if(!updatetrade($order,2,1)){
						$paystate=5;
					}
				}
				if(checkorder($order)){
					if(checkorder($order,1)){
						$order=$db2->select(3,"tb_trade","tradeid",array("orderid"=>$db2->select(3,'tb_trade','orderid',array('tradeid'=>$order)),"tradeid[!]"=>$order));
						if(!updatetrade($order,2,0)){
							$paystate=6;
						}
					}
				}
			}else{
				$paystate=3;
			}
		}
		if($paystate==1){	
			$value['title']='您的任性点交易订单：'.$id.' 付款成功';
			$value['orderid']=$order['tbid'];
			XingeApp::PushAccountAndroid(XG_ANDROID_ACCESS_ID, XG_ANDROID_SECRET_KEY, "付款通知",json_encode(array('title'=>$data['out_trade_no'])), 'rxd7');
			return true;
		}else{
			return false;
		}
	}
}

Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();
$notify->Handle(false);
